<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.keyword" placeholder="部门名称"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="queryKeyword">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="deptList" highlight-current-row v-loading="listLoading" @selection-change="selectChange"
			style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="40">
			</el-table-column>
			<el-table-column prop="name" label="部门名称" width="100">
			</el-table-column>
			<el-table-column prop="intro" label="部门简介" width="120">
			</el-table-column>
			<el-table-column prop="state" label="部门状态" width="80" :formatter="formatState">
			</el-table-column>
			<el-table-column prop="parent.name" label="上级部门" width="80">
			</el-table-column>
			<el-table-column prop="manager.username" label="管理者" width="90">
			</el-table-column>
			<el-table-column prop="createTime" label="创建时间">
			</el-table-column>
			<el-table-column prop="updateTime" label="修改时间">
			</el-table-column>
			<el-table-column prop="path" label="路径" width="70">
			</el-table-column>
			<el-table-column label="操作" width="150">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length === 0">批量删除</el-button>
			<el-pagination style="float: right;margin-top: 10px;" @size-change="handleSizeChange"
				@current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[10, 20, 50]"
				:page-size="100" layout="total, sizes, prev, pager, next, jumper" :total="total">
			</el-pagination>
		</el-col>

		<!-- 对话框 添加/修改 -->
		<el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" @close="dialogClose">
			<el-form :model="form" :rules="addFormRules">
				<el-input v-model="form.id" autocomplete="off" type="hidden"></el-input>
				<el-form-item label="部门名称" prop="name">
					<el-input v-model="form.name" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="部门简介" prop="intro">
					<el-input v-model="form.intro" autocomplete="off"></el-input>
				</el-form-item>
				<el-form-item label="选择状态">
					<el-radio v-model="form.state" :label="true">启用</el-radio>
					<el-radio v-model="form.state" :label="false">不启用</el-radio>
				</el-form-item>
				<el-form-item label="管理者">
					<!-- <el-input v-model="form.managerId" autocomplete="off" style="width: 70%;"></el-input> -->
					<el-select v-model="form.manager" placeholder="请选择管理者" clearable value-key="id">
						<el-option :label="emp.username" :value="emp" v-for="emp in emps"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="上级部门">
					<!-- <el-input v-model="form.parentId" autocomplete="off"></el-input> -->
					<el-cascader v-model="form.parent" :options="deptTree" clearable :props="{
			expandTrigger: 'hover',
			checkStrictly: true,
			label: 'name',
			value: 'id'
		}"></el-cascader>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="handleClose">取 消</el-button>
				<el-button type="primary" @click="handleSure">确 定</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
export default {
	data() {
		return {
			filters: {
				keyword: ''
			},
			deptList: {
			},
			currentPage: 1,
			pageSize: 10,
			// 总记录数
			total: 0,
			listLoading: false,
			sels: [],//列表选中列
			dialogFormVisible: false,
			form: {},
			addFormRules: {
				name: [
					{ required: true, message: '请输入部门名称', trigger: 'blur' }
				],
				intro: [
					{ required: true, message: '请输入部门名称', trigger: 'blur' }
				]
			},
			emps: [],
			deptTree: [],
      dialogTitle:''
		}
	},
	created() {
		this.loadDataPage();
		this.getEmps();
	},
	methods: {
		loadDataPage() {
			let pageQuery = {
				keyword: this.filters.keyword,
				currentPage: this.currentPage,
				pageSize: this.pageSize
			}
			this.$http.post("/dept", pageQuery).then(res => {
				this.deptList = res.data.data.pageList
				this.total = res.data.data.count
			})
		},
		//格式化state
		formatState(row) {
			return row.state === true ? '启用' : '未启用'
		},
		//改变每页总条数触发事件
		handleSizeChange(val) {
			console.log(val);
			this.pageSize = val
			this.loadDataPage();
		},
		//改变当前页触发事件
		handleCurrentChange(val) {
			console.log("当前页" + val);
			this.currentPage = val;
			this.loadDataPage();
		},
		queryKeyword() {
			this.currentPage = 1;
			this.pageSize = 10;
			this.loadDataPage();
		},
		//打开对话框
		handleAdd() {
		  this.dialogTitle = '添加'
			this.getDeptTree();//获取部门tree
			this.dialogFormVisible = true
		},
		//取消对话框
		handleClose() {
			this.dialogFormVisible = false;
			this.form = {};
		},
		//确定 发送添加/修改请求
		handleSure() {
			this.$confirm('确认提交吗？', '提示', {}).then(() => {
				//这里级联得到的parent会是一个数组
				//所以判断parent的类型
				if (this.form.parent) {
					if (this.form.parent instanceof Array) {//数组
						this.form.parentId = this.form.parent[this.form.parent.length - 1];//取数组的最后一个id值
						//因为这才是当前的父级id
					} else { //数字
						this.form.parentId = this.form.parent
					}
				}
				//赋值为null，不然parent就会是数组，传到后端，类型不匹配会报错
				this.form.parent = null;
				this.$http.put('/dept', this.form).then((res) => {
					if (res.data.success) {
						// this.addLoading = false;
						this.$message({
							message: res.data.message,
							type: 'success'
						});
					} else {
						this.$message({
							message: res.data.message,
							type: 'error'
						});
					}
					this.dialogFormVisible = false;
					this.loadDataPage();
					this.form = {};
				});
			});
		},
		//编辑
		handleEdit(index, row) {
		  this.dialogTitle = '修改'
			this.getDeptTree();//获取部门tree
			this.dialogFormVisible = true;
			// 复制数据，避免修改数据后点击取消仍会改变当前行数据的情况
			let copy = Object.assign({}, row)
			this.form = copy;//数据回显
			this.form.parent = this.form.parentId;//回显级联
		},
		// X
		dialogClose() {
			this.form = {}
		},
		//删除
		handleDel(row) {
			console.log(this.total, this.pageSize);
			this.$confirm('确认删除吗？', '提示', {}).then(() => {
				// this.addLoading = true;
				this.$http.delete('/dept/' + row.id).then((res) => {
					if (res.data.success) {
						// this.addLoading = false;
						this.$message({
							message: res.data.message,
							type: 'success'
						});
					} else {
						this.$message({
							message: res.data.message,
							type: 'error'
						});
					}
					//删除最后一页最后一项，使其跳回上一页
					this.loadAfterDeleteLastData();
					this.loadDataPage();//刷新
				});
			});
		},
		//批量选择
		selectChange(val) {
			console.log(val);
			let delArray = [];
			for (let i = 0; i < val.length; i++) {
				delArray[i] = val[i].id
			}
			this.sels = delArray;
			console.log(delArray);
		},
		//批量删除
		batchRemove() {
			this.$confirm('确认删除选中记录吗？', '提示', {
				type: 'warning'
			}).then(() => {
				this.$http.delete('/dept/batch/' + this.sels).then((res) => {
					this.$message({
						message: res.data.message,
						type: 'success'
					});
					this.loadAfterDeleteLastData();
					this.loadDataPage();
				});
			})
		},
		//获取员工列表，用于多选
		getEmps() {
			this.$http.get('/emp').then(res => {
				this.emps = res.data.data
			})
		},
		//查询部门tree
		getDeptTree() {
			this.$http.get('/dept/tree').then(res => {
				this.deptTree = res.data.data
			})
		},
    // 删除分页的最后一条数据后，跳到上一分页
    loadAfterDeleteLastData(){
      let deleteAfterPage = Math.ceil((this.total - 1) / this.pageSize)
      let deleteAfterCurrentPage = this.currentPage > deleteAfterPage ? deleteAfterPage : this.currentPage
      this.currentPage = deleteAfterCurrentPage < 1 ? 1 : deleteAfterCurrentPage
    }
	}
}

</script>

<style scoped></style>